#!/usr/bin/env python
#-*- coding:utf-8 -*-

import logging
from shorp.core.node import Node

VERSION = '20100318'
logger = logging.getLogger('shorp.interpreter')

class Interpreter:
    def interpret(self, node):
        pass
    def intent(self, intent=0):
        ret = ''
        while intent>0:
            ret = ret + '    '
            intent = intent - 1
        return ret

class SimpleInterpreter(Interpreter):
    def interpret(self, node, intent=0):
        tokens = node.getTokens()
        childs = node.getChilds()
        attrs = node.getAttrs()
        script = node.getScript()
        
        ret = self.intent(intent)
        if len(tokens)>0:
            for token in tokens:
                ret = ret + token[0] + token[1]
        
        if node.atidx>0 or len(attrs)>0:
            ret = ret + '('
            for i in range(node.atidx):
                ret = ret + '"'+node.getAtAttr(i)+'", '
            for k,v in attrs.iteritems():
                ret = ret + k + '="' + v+'", '
            ret = ret + ')'
            
        if script != '':
            ret = ret + '[^' + script + '$]'
        
        if len(childs)>0:
            ret = ret + '{' + chr(10)
            for c in childs:
                ret = ret + self.interpret(c, intent+1)
            ret = ret + self.intent(intent) + '}'
        
        ret = ret + chr(10)
        return ret

class XmlInterpreter(Interpreter):
    def interpret(self, node):
        name = node.getAttr('+')
        childs = node.getChilds()
        attrs = node.getAttrs(True)
        script = node.getScript()
        
        ret = ''
        if name != '':
            ret = '<'+name
        else:
            ret = '<Node'
            
        for k,v in attrs.iteritems():
            if k == '#':
                ret = ret + ' id="' + v + '"'
            elif k == ':':
                ret = ret + ' tpl="' + v + '"'
            elif k == '.':
                ret = ret + ' class="' + v + '"'
            elif k[0] == '@':
                ret = ret + ' at'+ k[1:]+'="' + v + '"'
            else:
                ret = ret + ' ' + k + '="' + v + '"'
        ret = ret + '>'
        
        if script != '':
            ret = ret + '<![CDATA[' + script + ']]>'
        
        for c in childs:
            ret = ret + self.interpret(c)
        
        if name != '':
            ret = ret + '</' + name + '>'
        else:
            ret = ret + '</Node>'
        
        return ret
        